package com.hzqy.commons.service;

import com.hzqy.commons.utils.MD5Util;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.XMLUtil;
import com.hzqy.web.login.SessionKey;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class IntegralService {
    protected static final Logger LOG = LoggerFactory.getLogger(IntegralService.class);
    public static final String CHARSET = "UTF-8";

    public Map<String, Object> getIntegral(String serverid){
        String url = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.itf_integral_query_url.getKey());
        String userName = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.itf_integral_query_userName.getKey());
        String key = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.itf_integral_query_key.getKey());
        String userKey = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.itf_integral_query_userKey.getKey());
        String sign = getSign(userName, userKey, serverid, key);
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("itvAccount",serverid);
        map.put("userName",userName);
        map.put("userkey",userKey);
        map.put("sign",sign);
        String param = createXMLStr(map);
        LOG.debug("url="+url+";param="+param);
        return post(url,param);
    }

    public static String createXMLStr(Map<String, Object> map){
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("ROOT");
        appendMap(root, map);
        return document.asXML();
    }

    public static void appendMap(Element ele,Map<String, Object> map){
        Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String,Object> field = it.next();
            Element e = ele.addElement(field.getKey());
            Object val = field.getValue();
            if(val instanceof Map){
                appendMap(e,(Map<String, Object>) val);
            }else{
                e.setText(String.valueOf(field.getValue()));
            }
        }
    }

    public static Map<String,Object> post(String urlStr,String param){
        OutputStream writer = null;
        HttpURLConnection httpConn = null;
        Map<String, Object> result = new HashMap<String, Object>();
        InputStream is = null;
        try{
            URL url = new URL(urlStr);
            httpConn = (HttpURLConnection) url.openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(20000);
            httpConn.setReadTimeout(30000);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Charset", CHARSET);
            httpConn.setRequestProperty("Content-Type", "application/xml");
            httpConn.setRequestMethod("POST");
            httpConn.connect();

            writer = httpConn.getOutputStream();
            writer.write(param.getBytes(CHARSET));
            writer.flush();

            int respCode = httpConn.getResponseCode();
            LOG.debug("respCode="+respCode);
            if (respCode == 200) {
                is = httpConn.getInputStream();
                result = XMLUtil.parseXML(getStringFromInputStream(is));
            }
            LOG.debug("查询结果="+result);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(httpConn != null)httpConn.disconnect();
            if(writer!=null){
                try{
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }

    /**
     * 获取InputStream中的文本
     */
    public static final String getStringFromInputStream(InputStream in){
        StringBuffer str = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(in, CHARSET));
            String temp = null;
            while((temp = reader.readLine()) != null){
                str.append(temp);
            }
        } catch (IOException e1) {
            LOG.error("IOException ", e1);
        }finally{
            try {
                if(reader != null) reader.close();
                if(in != null) in.close();
            } catch (IOException e) {
                LOG.error("IOException ", e);
            }
        }
        return str.toString();
    }


    public String getSign(String... strs){
        String encodeStr = "";
        for (String s : strs) {
            encodeStr += s;
        }
        return MD5Util.MD5Encode(encodeStr, "UTF-8").toUpperCase();
    }

}
